package com.comp5900.util;

import java.util.*;
import com.comp5900.impl.huffman.*;

public class HuffmanUtility {

	public static String getInorderTraversalOfEncodingTree(HuffmanTree tree){
		String traversal = "";

        if (tree instanceof HuffmanNode) {
        	traversal += "0" + getInorderTraversalOfEncodingTree( ((HuffmanNode)tree).leftchild );
        	traversal += "1" + getInorderTraversalOfEncodingTree( ((HuffmanNode)tree).rightchild );
        }
		
		return traversal;
	}

	public static void printCodes(HuffmanTree tree) {
		System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
		printCodes( tree, new Stack<Character>() );
	}

	private static void printCodes(HuffmanTree tree, Stack<Character> prefix) {
    	if (tree instanceof HuffmanLeaf<?>) {
        	HuffmanLeaf<?> leaf = (HuffmanLeaf<?>)tree;
 
            // print out character and frequency
            System.out.print(leaf.value + "\t" + leaf.frequency + "\t");
 
            // print out code for this leaf, which is just the prefix
            for (char bit : prefix)
            	System.out.print(bit);
            System.out.println();
 
        } 
        else if (tree instanceof HuffmanNode) {
        	HuffmanNode node = (HuffmanNode)tree;
 
        	// traverse left
        	prefix.push('0');
        	printCodes(node.leftchild, prefix);
        	prefix.pop();
 
        	// traverse right
        	prefix.push('1');
        	printCodes(node.rightchild, prefix);
        	prefix.pop();
        }
	}

}
